<template>
  <div class="demo-page">
    <div ref="line" id="line-container"></div>
  </div>
</template>

<script setup>
// 睡不着的时候，我不数羊，也不数星星，我数人生中的错误  --- auth by 福瓜
import * as echarts from 'echarts'
import { onMounted, onUnmounted, ref } from 'vue'

const line = ref()

const resizeObserver = ref()

const callback = (chart) => {
  return chart.resize()
}

onMounted(async () => {
  const res = (await window.$apis.getEcharts()) || []
  const config = {
    xAxis: {
      type: 'category',
      data: res.map((item) => item.date)
    },
    grid: {
      left: 40,
      right: 25,
      bottom: 50,
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const tips = params.map((item) => {
          return `体重${item.value}kg`
        })
        return tips.join(',')
      }
    },
    yAxis: {
      type: 'value',
      min: 68
    },
    series: [
      {
        data: res.map((item) => item.weight),
        type: 'line',
        smooth: true
      }
    ]
  }
  const el = line.value
  const chart = echarts.init(el)
  chart.setOption(config)
  resizeObserver.value = new ResizeObserver(() => callback(chart))
  resizeObserver.value.observe(el)
})
onUnmounted(() => {
  if (!line.value) return
  resizeObserver.value.unobserve(line.value)
})
</script>

<style scoped>
.demo-page {
  width: 100%;
  height: 100%;
}
#line-container {
  width: 100%;
  height: 100%;
}
</style>
